/**
 * 
 */
package com.aepona.solution.communication;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import com.aepona.solution.communication.utils.CommonUtils;

/**
 * @author Dhanushka Ariyasingha.
 */
public class ConnectionThread implements Runnable {

    private Socket socket;

    private Thread connectionThread = null;
    
    private ObjectInputStream inputStream;
    
    private ObjectOutputStream outputStream;
    
    private CommunicationMessage message = null;

    public ConnectionThread(final Socket socket) {

        this.socket = socket;

        connectionThread = new Thread(this);

    }

    public void start() {

        connectionThread.start();
        

    }
    
    public void join() throws InterruptedException {

        connectionThread.join();
        

    }

    public void closeConnection() throws IOException {

        inputStream.close();
        outputStream.close();
        socket.close();
    }

    public void run() {

        try {

            final StringBuilder stringBuilder = new StringBuilder();

            inputStream = new ObjectInputStream(socket.getInputStream());
            final Object object = inputStream.readObject();

            stringBuilder.append("Remote Socket Address :" + socket.getRemoteSocketAddress() + "|");

            if (object instanceof CommunicationMessage) {

                message = (CommunicationMessage) object;

                stringBuilder.append(message.getMessageHeader() + "|");

                CommonUtils.print("Server starting to process data !", stringBuilder.toString());

            }

            outputStream = new ObjectOutputStream(socket.getOutputStream());

        } catch (final IOException ioexception) {

            // TODO Auto-generated catch block
            ioexception.printStackTrace();

        } catch (final ClassNotFoundException classNotFoundException) {

            // TODO Auto-generated catch block
            classNotFoundException.printStackTrace();

        } catch (final Exception exception) {
            // TODO Auto-generated catch block
            exception.printStackTrace();

        }

    }
    
    public CommunicationMessage read() throws IOException {

        return message;

    }
    
    public void write(final CommunicationMessage message) throws IOException{
        
        outputStream.writeObject(message);
    }

}
